package com.powerhua.core.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Brian.Xie 
 */
public class DatabaseManager {

    private static final Log LOG = LogFactory.getLog(DatabaseManager.class);

    /**
     * 
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("proxool.dbPool");
        } catch (SQLException ex) {
            LOG.error("Can not get connection", ex);
        }

        return conn;
    }

    /**
     * 
     * @param conn
     */
    public static void closeConnection(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            LOG.error("Close connection fail", e);
        }
    }

    /**
     * 
     * @param rs
     */
    public static void closeResultSet(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            LOG.error("Close resultset fail", e);
        }
    }

    /**
     * 
     * @param ps
     */
    public static void closePreparedStatement(PreparedStatement ps) {
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException e) {
            LOG.error("Close preparedstatement fail", e);
        }
    }

    /**
     * 
     * @param stmt
     */
    public static void closeStatement(Statement stmt) {
        try {
            if(stmt != null) {
                stmt.close();
            }
        } catch(SQLException e) {
            LOG.error("Close statement fail", e);
        }
    }

    /**
     * 
     * @param conn
     * @param ps
     * @param stmt
     * @param rs
     */
    public static void closeConnection(Connection conn,
            PreparedStatement ps, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }

            if (ps != null) {
                ps.close();
            }

            if (stmt != null) {
                stmt.close();
            }

            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            LOG.error("Close database connection fail", e);
        }
    }
}
